<template>
  <div class="container">
    <div class="header">
      <h1>讲师管理</h1>
      <div class="actions">
        <el-button type="primary" @click="addInstructor">添加讲师</el-button>
      </div>
    </div>
    
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="讲师姓名">
          <el-input v-model="searchForm.teacherName" placeholder="请输入讲师姓名" clearable />
        </el-form-item>
        <el-form-item label="点赞数范围">
          <el-input-number v-model="searchForm.minLikes" :min="0" placeholder="最小值" />
          <span class="range-separator">-</span>
          <el-input-number v-model="searchForm.maxLikes" :min="0" placeholder="最大值" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="table-card">
      <el-table :data="teacherList" style="width: 100%" v-loading="loading">
        <el-table-column type="index" prop="id" label="ID" width="60" />
        <el-table-column label="头像" width="80">
          <template #default="scope">
            <div class="avatar-preview-container">
              <img
                style="width: 50px; height: 50px; border-radius: 50%; object-fit: cover;"
                :src="scope.row.teacherHeaderUrl || ''"
                :onerror="'this.style.display=\'none\'; this.nextElementSibling.style.display=\'flex\''"
              />
              <el-avatar
                v-if="!scope.row.teacherHeaderUrl"
                :size="50"
                style="display: none;">
                {{ scope.row.teacherName ? scope.row.teacherName.charAt(0) : '' }}
              </el-avatar>
              <el-button
                class="preview-btn"
                type="primary"
                size="small"
                circle
                @click="previewImage(scope.row.teacherHeaderUrl)"
                :disabled="!scope.row.teacherHeaderUrl">
                <el-icon><ZoomIn /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="teacherName" label="讲师姓名" width="120" />
        <el-table-column prop="teacherDescription" label="简介" min-width="350">
          <template #default="scope">
            <div class="description-cell">{{ scope.row.teacherDescription }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="teacherLikeNumbers" label="点赞数" width="80" />
        <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button size="small" @click="editInstructor(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteInstructor(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="头像预览" width="400px" append-to-body center>
      <div class="image-preview-dialog">
        <el-image
          style="width: 100%;"
          :src="previewImageUrl"
          fit="contain"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ZoomIn } from '@element-plus/icons-vue'
import { getTeacherPage, deleteTeacher } from '@/api/teacher'

const router = useRouter()
const loading = ref(false)
const teacherList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const previewVisible = ref(false)
const previewImageUrl = ref('')

// 搜索表单数据
const searchForm = reactive({
  teacherName: '',
  minLikes: null,
  maxLikes: null
})

// 添加讲师
const addInstructor = () => {
  router.push('/instructor/add')
}

// 编辑讲师
const editInstructor = (row) => {
  router.push(`/instructor/edit/${row.id}`)
}

// 删除讲师
const deleteInstructor = (row) => {
  ElMessageBox.confirm(
    `确定要删除讲师"${row.teacherName}"吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        const response = await deleteTeacher(row.id)
        if (response.code === 200) {
          ElMessage.success('删除成功')
          fetchData()
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      } catch (error) {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {})
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.teacherName = ''
  searchForm.minLikes = null
  searchForm.maxLikes = null
  currentPage.value = 1
  fetchData()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchData()
}

// 处理每页显示条数变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchData()
}

// 预览图片
const previewImage = (url) => {
  if (!url) return
  previewImageUrl.value = url
  previewVisible.value = true
}

const fetchData = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    
    // 添加搜索条件
    if (searchForm.teacherName) {
      params.teacherName = searchForm.teacherName
    }
    
    if (searchForm.minLikes !== null) {
      params.minLikes = searchForm.minLikes
    }
    
    if (searchForm.maxLikes !== null) {
      params.maxLikes = searchForm.maxLikes
    }
    
    const response = await getTeacherPage(
      params.pageNum, 
      params.pageSize, 
      params.teacherName, 
      params.minLikes, 
      params.maxLikes
    )
    
    if (response.code === 200 && response.data) {
      // 处理分页数据
      if (response.data.records) {
        teacherList.value = response.data.records
        total.value = response.data.total || 0
      } else {
        teacherList.value = response.data
        total.value = response.data.length || 0
      }
    } else {
      ElMessage.error(response.message || '获取讲师数据失败')
    }
  } catch (error) {
    console.error('获取讲师数据失败', error)
    ElMessage.error('获取讲师数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h1 {
      font-size: 24px;
      margin: 0;
    }
  }
  
  .search-card {
    margin-bottom: 20px;
    
    .search-form {
      display: flex;
      flex-wrap: wrap;
      
      .range-separator {
        margin: 0 5px;
      }
    }
  }
  
  .table-card {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .description-cell {
    white-space: normal;
    line-height: 1.5;
    max-height: 60px;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }

  .avatar-preview-container {
    position: relative;
    width: 50px;
    height: 50px;
    margin: 0 auto;
    
    .preview-btn {
      position: absolute;
      right: -10px;
      bottom: -10px;
      opacity: 0;
      transition: opacity 0.3s;
    }
    
    &:hover .preview-btn {
      opacity: 1;
    }
  }

  .image-preview-dialog {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;
  }
}
</style> 